package com.yimiyisu.kooteam.server;

import com.yimiyisu.kooteam.constant.ContentTypeConstant;
import com.yimiyisu.kooteam.constant.FileTypeConstant;
import com.yimiyisu.kooteam.utils.FileUri;
import com.zen.ZenData;
import com.zen.ZenResult;
import com.zen.domain.App;
import com.zen.domain.CheckResult;
import com.zen.domain.api.ApiSchema;
import com.zen.enums.ZenAction;
import com.zen.enums.ZenException;
import com.zen.enums.ZenMethod;
import com.zen.enums.ZenRole;
import com.zen.h.j;
import com.zen.kit.StringKit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.smartboot.http.common.enums.HeaderNameEnum;
import org.smartboot.http.common.enums.HeaderValueEnum;
import org.smartboot.http.common.enums.HttpMethodEnum;
import org.smartboot.http.common.enums.HttpStatus;
import org.smartboot.http.server.HttpRequest;
import org.smartboot.http.server.HttpResponse;
import org.smartboot.http.server.HttpServerHandler;
import org.smartboot.http.server.ServerHandler;

import java.io.IOException;
import java.io.InputStream;
import java.net.URL;
import java.nio.charset.StandardCharsets;
import java.util.*;
import java.util.concurrent.CompletableFuture;

public class DefaultHttpServerHandler extends HttpServerHandler implements ServerHandler<HttpRequest, HttpResponse> {
    private static final Logger a = LoggerFactory.getLogger(com.zen.f.c.class);
    private static final String b = "/api/";
    private static final String c = "/do/";
    private static final Map<String, String> accessControlAllowMap = new HashMap<>() {
        {
            this.put("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
            this.put("Access-Control-Allow-Credentials", "true");
            this.put("Access-Control-Allow-Headers", "*");
        }
    };

    @Override
    public void handle(HttpRequest request, HttpResponse response) throws Throwable {
        try {// /api/auth/login
            String requestURI = request.getRequestURI();
            System.out.println("process uri:" + requestURI);
            for (Map.Entry<String, String> entry : accessControlAllowMap.entrySet()) {
                response.setHeader(entry.getKey(), entry.getValue());
            }

            if (com.zen.d.a.g()) {
                response.setHeader("Access-Control-Allow-Origin", "*");
                response.setHeader("Access-Control-Allow-Private-Network", "true");
                if (HttpMethodEnum.OPTIONS.getMethod().equals(request.getMethod())) {
                    return;
                }
            }

            if (requestURI.startsWith("/do/")) {
                processDo(request, response, requestURI);
                return;
            }
            // /api/auth/login
            if (requestURI.startsWith("/api/")) {
                processApi(request, response, requestURI);
                return;
            }

            if (!dd.a(response, request, requestURI)) {
                response.write(ZenException.RESOURCE_NOT_FOUND.asBytes());
            }
        } catch (Throwable var12) {
            response.write(ZenResult.fail(var12).toBytes());
            a.error("500", var12);
        }
    }

    private void processApi(HttpRequest request, HttpResponse response, String requestURI) throws IOException {
        // /api/auth/login
        requestURI = requestURI.substring("/api/".length());
        ZenResult zenResult = com.zen.f.a.a(response, request, requestURI, new ZenData(request));
        if (zenResult == null) {
            zenResult = ZenResult.fail("内部错误");
        }
        if (zenResult.getAction() == ZenAction.ORIGINAL.getValue()) {
            return;
        }
        response.write(zenResult.toBytes());
    }

    // /do/list/flow_template 需要找到资源图片,然后放到 \vue\public 目录下面
//    {"success":true,"action":0,"data":[
//            {"id":"6756a7e291e9d9","title":"block","preview":"/templates/other/block.png"}
    private void processDo(HttpRequest request, HttpResponse response, String requestURI) throws IOException {
        requestURI = requestURI.substring("/do/".length());
        int var14 = requestURI.indexOf("/");
        if (var14 == -1) {
            response.write(ZenException.ENGINE_API_NOT_FOUND.asBytes());
            return;
        }

        ApiSchema apiSchema = com.zen.d.a.c(requestURI);
        if (apiSchema == null) {
            response.write(ZenException.ENGINE_API_NOT_FOUND.asBytes());
            return;
        }

        ZenData zenData = new ZenData(request);
        ZenRole zenRole = ZenRole.getByValue(apiSchema.getRole());
        String var8 = apiSchema.getType();
        String var9 = String.format("%s/%s", var8, apiSchema.getName());
        CheckResult checkResult = j.a(zenData, zenRole, ZenMethod.POST, var9, request);
        if (checkResult.isEnd()) {
            response.write(checkResult.getResult().toBytes());
            return;
        }

        ZenResult zenResult = com.zen.h.a.b().a(apiSchema, zenData);
        zenResult = j.a(checkResult, zenData, zenResult);
        // TODO 数据处理
        response.write(zenResult.toBytes());
    }

    @Override
    public void handle(HttpRequest var1, HttpResponse var2, CompletableFuture<Object> var3) throws Throwable {
        super.handle(var1, var2, var3);
    }


    public static class dd {
        private static final Logger a = LoggerFactory.getLogger(dd.class);
        private static final String b = "../";
        private static final String c = "Content-Type";
        private static final String d = "Last-Modified";
        private static final String e = (new Date()).toString();
        private static final String f = "html";
        private static final String g = "home";
        private static String h;
        private static final Map<String, String> i = new HashMap<>();

        public static void a() {
            Set<String> var0 = i.keySet();
            for (String var2 : var0) {
                i.remove(var2);
                a(var2);
            }
        }

        public static boolean a(HttpResponse var0, HttpRequest var1, String var2) throws IOException {
            String var3 = StringKit.fileExt(var2);
            String var4 = ContentTypeConstant.a(var3);
            if (var2.contains("../")) {
                return false;
            } else {
                var0.setHeader("Last-Modified", e);
                var0.setHeader("Content-Type", var4);
                if (FileTypeConstant.m.contains(var3)) {
                    var0.setHeader(HeaderNameEnum.CONTENT_ENCODING.getName(), HeaderValueEnum.GZIP.getName());
                }

                String var5;
                if (StringKit.isEmpty(var3)) {
                    if (com.zen.h.i.a != null) {
                        if (var2.contains("install")) {
                            var0.setHeader("Content-Type", ContentTypeConstant.a("json"));
                            ZenResult var6 = com.zen.h.i.a.a(var1, var2);
                            var0.write(var6.toBytes());
                            return true;
                        }

                        var5 = a("install");
                    } else {
                        var5 = a("home");
                    }
                } else {
                    if (!"html".equals(var3)) {
                        try {
                            URL var15 = FileUri.a(var2);
                            if (var15 == null) {
                                var0.setHttpStatus(HttpStatus.NOT_FOUND);
                                return true;
                            }

                            var0.setHeader("Cache-Control", "public, max-age=31536000");

                            try {
                                InputStream var7 = var15.openStream();

                                try {
                                    var0.setHttpStatus(HttpStatus.OK);
                                    var0.write(var7.readAllBytes());
                                } catch (Throwable var11) {
                                    if (var7 != null) {
                                        try {
                                            var7.close();
                                        } catch (Throwable var10) {
                                            var11.addSuppressed(var10);
                                        }
                                    }

                                    throw var11;
                                }

                                if (var7 != null) {
                                    var7.close();
                                }
                            } catch (IOException var12) {
                                return false;
                            }
                        } catch (Exception var13) {
                            throw new RuntimeException(var13);
                        }

                        var0.setHttpStatus(HttpStatus.NOT_FOUND);
                        return true;
                    }

                    String var14 = var2.substring(1, var2.length() - var3.length() - 1);
                    if (var14.equals("index")) {
                        var5 = a("home");
                    } else {
                        var5 = a(var14);
                    }
                }

                if (com.zen.d.a.b("iframe") == null) {
                    var0.addHeader("x-frame-options", "sameorigin");
                }

                var0.setContentType("text/html;charset=utf-8");
                assert var5 != null;
                var0.write(var5.getBytes(StandardCharsets.UTF_8));
                return true;
            }
        }

        private static String a(String var0) {
            if (!i.containsKey(var0)) {
                String var1 = com.zen.d.a.f(var0 + ".html");
                if (StringKit.isEmpty(var1)) {
                    return null;
                }

                String var2 = com.zen.d.a.m();
                HashMap<String, String> var3 = new HashMap<>();
                App var4 = com.zen.h.e.a();
                h = var4.getTitle();
                if (h == null) {
                    h = "";
                }

                String var5 = com.zen.d.a.b("cdnDomain", "");
                var3.put("title", h);
                var3.put("cdnDomain", var5);
                String var6 = com.zen.d.a.b("uiVersion");
                if (!StringKit.isEmpty(var5) && !StringKit.isEmpty(var6)) {
                    String var7 = com.zen.d.a.b("appVersion");
                    var3.put("corePath", var5 + "/zeto/" + var6);
                    var3.put("appPath", var5 + "/" + com.zen.d.a.a() + "/" + var7 + "/");
                } else {
                    var3.put("corePath", "/" + var2);
                    var3.put("appPath", "/" + var2 + "/");
                }

                String var8;
                for (Iterator<String> var9 = var3.keySet().iterator(); var9.hasNext(); var1 = var1.replace("${" + var8 + "}", (CharSequence) var3.get(var8))) {
                    var8 = (String) var9.next();
                }

                i.put(var0, var1);
                i.put(var0, var1);
            }

            return ((String) i.get(var0)).replace("${sid}", StringKit.shortId());
        }
    }
}
